<?php

namespace app\api\controller\kuyou\applet;

use app\api\model\kuyou\applet\Goods;
use app\api\model\kuyou\applet\Warehousing as Warehousings;
use think\Db;
/**
 * 入库单接口
 */
class Warehousing extends Common
{
    protected $noNeedRight = ['getdetail','getpurchaseorder','period','checkpurchase','getbranch'];

    /**
     * 获取入库单
     * @ApiMethod (POST)
     * @param int $page 页码
     * @param int $limit 每页条数
     * @param string $name 入库单名称
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->post('page');
            $page = empty($page)?1:$page;
            $limit = $this->request->post('limit');
            $limit = empty($limit)?config('app_limit'):$limit;

            $where = [];
            $code = $this->request->post('purchase_code');
            if(!empty($code)){
                $where['purchase_code'] = ['like','%'.$code.'%'];
            }
            $purchase_time = $this->request->post('purchase_time');
            if(!empty($purchase_time)){
                $str = explode('~',$purchase_time);
                if(isset($str[0]) && isset($str[1])){
                    $where['purchase_time'] = ["BETWEEN", [strtotime($str[0]),strtotime($str[1])]];
                }
            }
            $business_type = $this->request->post('business_type');
            if($business_type!=null && $business_type!==''){
                $where['business_type'] = $business_type;
            }
            $suppliers_id = $this->request->post('suppliers_id');
            if(!empty($suppliers_id)){
                $where['suppliers_id'] = $suppliers_id;
            }
            $keyword = $this->request->post('keyword');
            if(!empty($keyword)){
                $where['purchase_code'] = ['like','%'.$keyword.'%'];
            }

            $sort_field = $this->request->post('sort_field');
            $sort_field = empty($sort_field)?'purchase_code':$sort_field;

            $sort_type = $this->request->post('sort_type');
            $sort_type = empty($sort_type)?'DESC':$sort_type;

            $result = Warehousings::getList($where,$page,$limit,$sort_field,$sort_type);

            if(isset($result['list']) && isset($result['count'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取入库单详情
     * @ApiMethod (POST)
     * @param string $purchase_code
     */
    public function getdetail()
    {
        if ($this->request->isPost()) {
            $purchase_code = $this->request->post('purchase_code');
            if(empty($purchase_code)){
                $this->error('请输入查询参数','',500);
            }
            $result = Warehousings::getDetail($purchase_code);
            if($result['status']==200){
                $this->success('查询成功',$result['msg'],200);
            }else{
                $this->error($result['msg'],'',$result['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 添加入库单
     * @ApiMethod (POST)
     * @param array $detail 入库单数据
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $ret = Warehousings::addDetail($data);
            if($ret['status']==200){
                $this->success('添加成功',$ret['msg'],200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 更新入库单
     * @ApiMethod (POST)
     * @param array $detail 入库单数据
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $ret = Warehousings::editDetail($data);
            if($ret['status']==200){
                $this->success('更新成功','',200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 删除入库单
     * @ApiMethod (POST)
     * @param int $purchase_code 入库单编号
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $purchase_code = $this->request->post('purchase_code');
            $ret = Warehousings::delDetail($purchase_code);
            if($ret['status']==200){
                $this->success('删除成功',$ret['msg'],200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 审核入库单
     * @ApiMethod (POST)
     * @param int $purchase_code 入库单编号
     */
    public function examine()
    {
        if ($this->request->isPost()) {
            $purchase_code = $this->request->post('purchase_code');
            $type = $this->request->post('type');
            if($type=='examine'){
                $ret = Warehousings::examine($purchase_code);
                $msg = '审核成功';
            }else{
                $ret = Warehousings::examinef($purchase_code);
                $msg = '反审核成功';
            }
            if($ret['status']==1){
                $this->success($msg,$ret['msg'],200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 格式化序列号
     * @ApiMethod (POST)
     * @param array $purchase_code 入库单编号
     */
    public function period(){
        if ($this->request->isPost()) {
            $data = $_POST;
            if(isset($data['period_period'])){
                $this->success('格式化成功',['ser'=>unserialize($data['period_period'])],200);
            }elseif (isset($data['chose_serial'])){
                $chose_serial = $data['chose_serial'];
                $serial_data = [];
                foreach ($chose_serial as $chose_serial_k=>$chose_serial_v){
                    $serial_data[] = ['serial'=>$chose_serial_v,'remark'=>''];
                }
                $this->success('格式化成功',['num'=>sizeof($serial_data),'ser'=>serialize($serial_data)],200);
            }
            $params = $this->request->post("stock/a");
            $data = [];
            foreach ($params['serial'] as $k=>$v){
                if(!empty($v)){
                    $data[] = [
                        'serial' => $v,
                        'remark' => (isset($params['remark'][$k])?$params['remark'][$k]:''),
                    ];
                }
            }
            $this->success('格式化成功',['num'=>sizeof($data),'ser'=>serialize($data)],200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 盘盈
     * @ApiMethod (POST)
     * @param int $purchase_code 购货订单编号
     */
    public function checkpurchase(){
        if ($this->request->isPost()) {
            $purchase_code = $this->request->post('purchase_code');
            $type = $this->request->post('type');
            $order_type = $this->request->post('order_type');
            $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
            $setList = [];
            foreach ($set as $set_k=>$set_v){
                if(!empty($set_v['set'])){
                    $set_v['set'] = unserialize($set_v['set']);
                }
                $setList[$set_v['name']] = $set_v;
            }
            //数量价格格式化
            $price_decimal = $setList['price_decimal']['value'];

            switch ($type){
                case 1:
                    //盘点盘盈
                    if(!empty($purchase_code)){
                        $row = Db::name('kuyou_inventory')->where(['purchase_code'=>$purchase_code])->find();
                        if($order_type==1){
                            $info = Db::name('kuyou_inventory_info')->where(['purchase_code'=>$purchase_code,'profit'=>['>',0]])->select();
                        }else{
                            $info = Db::name('kuyou_inventory_info')->where(['purchase_code'=>$purchase_code,'profit'=>['<',0]])->select();
                        }
                        foreach ($info as $info_k=>$info_v){
                            $goods = Db::name('kuyou_goods')->where(['id'=>$info_v['goods_id']])->find();
                            $info[$info_k]['goods'] = $goods;

                            //获取成本单价
                            $balance_unit=0;
                            $map = [
                                'goods_code' => $goods['goods_code'],
                                'store' => $info_v['stores_id'],
                                'attr_id' => $info_v['goods_attr'],
                            ];
                            $goodsInfo = (new Goods())->getGoodsInfo($map);
                            $unitData = isset($goodsInfo['msg']['price_data'])?$goodsInfo['msg']['price_data']:[];
                            if($goodsInfo['status']!=200){
                                $this->error('商品信息获取错误');
                            }else{
                                foreach ($unitData as $unitData_k=>$unitData_v){
                                    if($unitData_v['id']==$goods['unit_id']){
                                        $balance_unit = $unitData_v['purchase'];
                                    }
                                }
                            }
                            $balance_cost = $balance_unit*$info_v['profit'];
                            $info[$info_k]['unit_price'] = round($balance_unit,$price_decimal);
                            $info[$info_k]['price'] = round($balance_cost,$price_decimal);
                            $info[$info_k]['unit'] = $goodsInfo['msg']['price_data'];
                        }
                        $row['info_list'] = $info;
                    }
                    break;
                case 2:
                    //序列号盘盈
                    if(!empty($purchase_code)){
                        $row = Db::name('kuyou_inventory_serial')->where(['purchase_code'=>$purchase_code])->find();
                        if($order_type==1){
                            $info = Db::name('kuyou_inventory_serial_info')->where(['purchase_code'=>$purchase_code,'inventory'=>['>',0]])->select();
                        }else{
                            $info = Db::name('kuyou_inventory_serial_info')->where(['purchase_code'=>$purchase_code,'loss'=>['>',0]])->select();
                        }
                        foreach ($info as $info_k=>$info_v){
                            $goods = Db::name('kuyou_goods')->where(['id'=>$info_v['goods_id']])->find();
                            $info[$info_k]['goods'] = $goods;

                            //获取成本单价
                            $balance_unit=0;
                            $map = [
                                'goods_code' => $goods['goods_code'],
                                'store' => $info_v['stores_id'],
                                'attr_id' => $info_v['goods_attr'],
                            ];
                            $goodsInfo = (new Goods())->getGoodsInfo($map);
                            $unitData = isset($goodsInfo['msg']['price_data'])?$goodsInfo['msg']['price_data']:[];
                            if(empty($unitData)){
                                $this->error('商品信息获取错误');
                            }else{
                                foreach ($unitData as $unitData_k=>$unitData_v){
                                    if($unitData_v['id']==$goods['unit_id']){
                                        $balance_unit = $unitData_v['purchase'];
                                    }
                                }
                            }

                            $goods_code    = isset($goods['goods_code'])?$goods['goods_code']:'';
                            $stores_id     = isset($info_v['stores_id'])?$info_v['stores_id']:'';
                            $attribute_id  = isset($info_v['goods_attr'])?$info_v['goods_attr']:'';
                            $where = [];
                            $where['store_status'] = '1';
                            $where['goods_code'] = $goods_code;
                            $where['stores_id'] = $stores_id;
                            if($attribute_id){
                                $where['attribute_id'] = $attribute_id;
                            }
                            $serial = Db::name('kuyou_goods_serial')->where($where)->column('serial');

                            $serial_arr = [];$inventory = 0;
                            if(isset($info_v['period_period'])){
                                $serial_pds = unserialize($info_v['period_period']);
                                foreach ($serial_pds as $serial_pds_k=>$serial_pds_v){
                                    if(!in_array($serial_pds_v['serial'],$serial)){
                                        $inventory+=1;
                                        $serial_arr[] = ['serial'=>$serial_pds_v['serial'],'remark'=>''];
                                    }
                                }
                            }

                            $info[$info_k]['profit'] = $inventory;
                            $balance_cost = $balance_unit*$inventory;
                            $info[$info_k]['unit_price'] = round($balance_unit,$price_decimal);
                            $info[$info_k]['price'] = round($balance_cost,$price_decimal);
                            $info[$info_k]['unit'] = $goodsInfo['msg']['price_data'];
                            $info[$info_k]['period'] = $serial_arr;
                        }
                        $row['info_list'] = $info;
                    }
                    break;
                default:
                    $row = [];
                    break;
            }
            if(empty($row)){
                $this->error('查询错误','',500);
            }
            $this->error('查询成功',$row,200);
        }else{
            $this->error('请求方式错误','',250);
        }
    }
}
